package cn.hl.user.service.impl;

import cn.hl.basic.exception.BusinessException;
import cn.hl.basic.service.impl.BaseServiceImpl;
import cn.hl.basic.util.Md5Utils;
import cn.hl.basic.util.StrUtils;
import cn.hl.user.domain.Logininfo;
import cn.hl.user.domain.User;
import cn.hl.user.dto.UserDto;
import cn.hl.user.mapper.LogininfoMapper;
import cn.hl.user.mapper.UserMapper;
import cn.hl.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 手机号码注册
     * @param userDto
     */
    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String confirmPwd = userDto.getConfirmPwd();
        // 1.校验参数是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) ||
            StringUtils.isEmpty(pwd) || StringUtils.isEmpty(confirmPwd)) {
            throw new BusinessException("信息不能为空！");
        }
        // 2.校验两次输入的密码是否一样
        if (!pwd.equals(confirmPwd)) {
            throw new BusinessException("输入的密码不一致！");
        }
        // 3.校验手机验证码是否过期，是否正确
        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        if (codeObj == null) {
            throw new BusinessException("验证码已过期，请重新获取！");
        }
        if (!codeObj.toString().split(":")[0].equals(phoneCode)) {
            throw new BusinessException("验证码错误，请重新输入！");
        }
        // 4.保存到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 4.1先保存logininfo
        logininfoMapper.add(logininfo);
        // 4.2再保存user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    /**
     * 邮箱注册
     * @param userDto
     */
    @Override
    public void emailRegister(UserDto userDto) {
        String email = userDto.getEmail();
        String emailCode = userDto.getEmailCode();
        String pwd = userDto.getPwd();
        String confirmPwd = userDto.getConfirmPwd();
        // 1.校验参数是否为空
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd)
                || StringUtils.isEmpty(confirmPwd) || StringUtils.isEmpty(emailCode)) {
            throw new BusinessException("信息不能为空！");
        }
        // 2.校验两次输入的密码是否一致
        if (!pwd.equals(confirmPwd)) {
            throw new BusinessException("两次输入的密码不一致！");
        }
        // 3.校验邮箱验证码是否过期，是否正确
        Object codeObj = redisTemplate.opsForValue().get("register:" + email);
        if (codeObj == null) {
            throw new BusinessException("验证码已过期，请重新获取！");
        }
        if (!codeObj.toString().split(":")[0].equals(emailCode)) {
            throw new BusinessException("验证码错误，请重新输入！");
        }
        // 4.保存到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 4.1先保存logininfo
        logininfoMapper.add(logininfo);
        // 4.2再保存user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        if (userDto.getPhone() == ""){
            user.setUsername(userDto.getEmail());
        } else {
            user.setUsername(userDto.getPhone());
        }
        user.setPhone(userDto.getPhone());
        user.setEmail(userDto.getEmail());
        // 获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        // 使用工具类深度拷贝
        BeanUtils.copyProperties(user,logininfo);
        // 设置当前对象为用户
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    public void add(User user) {
        // 获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        // 添加logininfo
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        // 添加user
        super.add(user);
    }

    @Override
    public void delete(Long id) {
        // 获取登录信息的id
        Long logininfoId = userMapper.findById(id).getLogininfoId();
        // 删除logininfo
        logininfoMapper.delete(logininfoId);
        // 删除user
        super.delete(id);
    }

    @Override
    public void update(User user) {
        // 获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        // 获取logininfo对象的id
        Long logininfoId = userMapper.findById(user.getId()).getLogininfoId();
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(logininfoId);
        // 修改logininfo
        logininfoMapper.update(logininfo);
        // 修改user
        super.update(user);
    }
}
